import RPi.GPIO as GPIO
import time
import datetime as dt
# init func
def init(pin_list):
    GPIO.setmode(GPIO.BCM)
    GPIO.setup(pin_list, GPIO.OUT)
    GPIO.output(pin_list, GPIO.LOW)

# util func
def food_switch(pinlist, duration, is_test=True):
	#test_loop(ch_list, frequency)
    if is_test:
        print('virtual switch, duration = %d sec' % (duration))
    else:
        print('real switch, duration = %d sec' % (duration))
        GPIO.output(pinlist, GPIO.HIGH)
        time.sleep(duration)
        GPIO.output(pinlist, GPIO.LOW)

def s2date(s):
    return dt.date(int(s[:4]), int(s[4:6]), int(s[7:]))
    

def is_on_time(start_date_s, stop_date_s):
    fmt = '%Y-%m-%d-%H.%M.%S'
    curr_tm = time.localtime(time.time())
    start_tm = time.strptime(start_date_s, fmt)
    stop_tm = time.strptime(stop_date_s, fmt)
    if curr_tm > start_tm and curr_tm < stop_tm:
        return 1
    else:
        if curr_tm < start_tm:
            diff_sec = time.mktime(start_tm) - time.mktime(curr_tm)
            print('will start after %d sec' % int(diff_sec))
            return 0
        else:
            print('Already out of date.')
            return -1

if __name__=='__main__':
    is_test = False
    #is_test = True
    start_date_s = '2020-10-20-16.27.00'
    stop_date_s  = '2020-10-20-16.30.00'
    switch_list = [1,2,3,4,5,6,7,10,11,12,13] # 1-based indices
    pin_list = [2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
    duration = 4 # sec of pulse
    interv_wait = 1 # sec to wait for next pulse
    init(pin_list)
    is_switch = False
    while(1):
        time_status = is_on_time(start_date_s, stop_date_s)
        if time_status == 1:
            if not is_switch:
                food_switch(pin_list, duration, is_test)
                is_switch = True
            time.sleep(interv_wait)
        elif time_status == 0:
            GPIO.output(pin_list, GPIO.LOW)
            time.sleep(1)
        else:
            break
